package com.mioto.ld.communication.mqtt;

import com.mioto.ld.communication.mqtt.protocol.ReceiptStrategyContext;
import com.mioto.ld.utils.SpringBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.nio.charset.StandardCharsets;

/**
 * @author mioto-qinxj
 * @date 2024/5/6
 * @desc Mqtt的回调
 */
@Slf4j
public class MqttClientCallback implements MqttCallbackExtended {

    private Integer mqttClientId;

    public MqttClientCallback(Integer mqttClientId){
        this.mqttClientId = mqttClientId;
    }

    /**
     * 订阅后得到的消息处理
     * @param topic
     * @param message
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        String data = new String(message.getPayload(), StandardCharsets.UTF_8);
        log.info("接收消息主题 - {} ,消息内容 - {}",topic,data);
        SpringBeanUtil.getBean(ReceiptStrategyContext.class).resolver(mqttClientId,data);
    }

    @Override
    public void connectComplete(boolean b, String s) {
        MqttHelper.mqttClients.forEach((k, v) -> {
            try {
                if (k.equals(mqttClientId)) {
                    log.info("mqtt重连成功 mqttClientId - {} 已连接", v.getMqttClientId());
                    v.sub(v.getSubTopic());
                }
            } catch (MqttException e) {
                log.error("mqtt重连失败 - {}",e,e.getMessage());
            }
        });
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.debug("发布消息成功");
    }

    @Override
    public void connectionLost(Throwable throwable) {
        log.info("MQTT连接断开", throwable);
    }

}
